<template>
    <div class="wrapper">
        <div class="boxWrapper tabbox">
            <el-tabs v-model="currentName"  v-if="showTabOne">
                <el-tab-pane label="巡视路径设置" name="1">
                     <span slot="label"><i class="iconfont">&#xe639;</i> 巡视路径设置</span>
                </el-tab-pane>
                <el-tab-pane label="巡视记录" name="2"  v-if="showTabTwo">
                     <span slot="label"><i class="iconfont">&#xe671;</i> 巡视记录</span>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="content" v-show="shouldShowTabOne">
            <div class="left-wrapper">
                <div class="top-content">
                        <div class="bg">
                        <div class="text">智能与数字化<span>工作台</span></div>
                        <el-button icon="el-icon-upload" size="medium" class="addBtn" type="primary" @click="dialogAsTemp = true,dialogTitle = '新增'" v-if="showRoleModuleAdd" >新增巡视项目</el-button>
                        </div>
                </div>
                <div class="left-wrapper-con">
                    <div v-for="item in TempTreeList" :key="item.id" :class="currentBoxId == item.id ? 'xsItem boxWrapper current' : 'xsItem boxWrapper'" @click="handleChangeTempTreeItem(item)">
                        <i class="iconfont select" v-if="currentBoxId == item.id">&#xe62f;</i>
                        <div class="name">{{ item.name }}</div>
                        <div class="btn-group">
                            <el-link type="primary" :underline="false" icon="el-icon-setting" @click.stop="handleSaveAsTempDialog(item)" v-if=" showRoleModuleEdit">设置成模板</el-link>
                            <el-link type="success" :underline="false" icon="el-icon-edit" @click.stop="handleEditAsTempDialog(item)" v-if=" showRoleModuleEdit">修改</el-link>
                            <el-link type="danger" :underline="false" icon="el-icon-delete" @click.stop="handleDelAsTempDialog(item)" v-if="showRoleModuleDel">删除</el-link>
                        </div>
                    </div>
                </div>    
            </div>
            <cardBox class="right-wrapper" title="目录" icon="&#xe6f2;" v-if="currentName == '1'">
            <template #right>
                <el-button type="primary" round size="mini" icon="el-icon-download" @click="handleImportTempTree" v-if="showRoleModuleEdit">导入模板</el-button>
            </template>
            <div class="menu-wrapper">
                <div class="table-tips">📝支持在目录节点上右键唤出操作菜单，选择菜单项执行相应功能</div>
                <div class="tree-wrapper">
                    <treeMenu :treeData="menuByTempTree" name="lable" isRightMenu
                    @addMenuItem="handleAddMenubyTemp" 
                    @editMenuItem="handleAddMenubyTemp"
                    @delMenuItem="handleDelMenubyTemp" 
                    :showRoleAdd="showRoleModuleAdd"
                    :showRoleDel="showRoleModuleDel"
                    :showRoleEdit="showRoleModuleEdit"
                    v-if="menuByTempTree.length > 0"/>

                    <noData showMenuBtn v-if="menuByTempTree.length == 0 && showRoleModuleAdd" @handleAddMenu="handleAddMenubyTemp({node:{}},0,1)" descriptionMenu="点击下方按钮创建首个目录，或导入模板快速开始"/>
                    
                </div>
            </div>
       </cardBox>
        </div>

        <visitationList v-if="shouldShowTabTwo" :menuSelect="TempTreeList" :stationId="stationId"></visitationList>

        <!-- 弹窗部分 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogAsTemp" width="500px"  v-dialogDrag :before-close="handleCancelAsTemp">
            <div>
            <el-form class="templateForm" ref="templateAsForm" :model="templateAsForm" label-width="100px">
                <el-form-item label="名称" prop="name"
                :rules="[
                    { required: true, message: '请输入名称'},
                ]">
                    <el-input placeholder="请输入" v-model="templateAsForm.name"  maxlength="30" show-word-limit></el-input>
                    </el-form-item>
                    <el-form-item>
                    </el-form-item>
                </el-form>
            </div>
            <div class="dialog-footer">
                <el-button @click="handleCancelAsTemp" icon="el-icon-circle-close" size="small" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleSaveAsTemp" icon="el-icon-circle-check" size="small" class="confirm-btn">保存名称</el-button>
            </div>
        </el-dialog>

        <el-dialog title="菜单配置" :visible.sync="dialogMenuVisibleByTemp" width="40%" v-dialogDrag :before-close="handleCloseDialogMenu">
            <el-form :model="menuFormByTemp" label-width="100px" size="medium" ref="menuFormByTemp">
                <el-form-item label="名称" required prop="treeName"
                :rules="[
                    { required: true, message: '请输入名称'},
                ]">
                    <el-input v-model="menuFormByTemp.treeName" placeholder="请输入名称" maxlength="30" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="检查内容">
                    <el-input v-model="menuFormByTemp.request" placeholder="请输入检查内容" type="textarea" maxlength="300" show-word-limit
    :rows="6"></el-input>
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="handleCloseDialogMenu" icon="el-icon-circle-close" size="small" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleSaveDialogMenu" icon="el-icon-circle-check" size="small" class="confirm-btn">保存配置</el-button>
            </div>
        </el-dialog>

        <el-dialog title="导入模板" :visible.sync="importTempDialog" width="700px" v-dialogDrag>
            <el-form :model="menuFormByTemp" label-width="100px" size="medium">
                <el-form-item label="模板">
                <el-select v-model="moduleSelect" placeholder="请选择" @change="handleChangeImportTree">
                    <el-option
                    v-for="item in moduleSelectList"
                    :key="item.tempID"
                    :label="item.name"
                    :value="item.tempID">
                    </el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="目录">
                <div class="menuList-wrapper">
                    <treeMenu :treeData="importTreeList" name="lable" 
                    @menuLeftClick="handleDialogLeftClick"
                    v-if="importTreeList.length > 0"/>
                    <div v-else>
                        <noData showMenu />
                    </div>
                </div>
                
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button @click="importTempDialog = false" size="small" icon="el-icon-circle-close" class="cancel-btn">取消</el-button>
                <el-button type="primary" @click="handleImportTemp(0)" size="small" icon="el-icon-download" class="confirm-btn">导入</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import cardBox from "@/components/base/cardBox.vue";
import {getInspectionTempsnew,SaveAsTemp,InspectionTypeAdd,InspectionTypeEdit,InspectionTypeDel,inspectionDataGetTree,InspectionTreeAdd,InspectionTreeEdit,InspectionTreeDel,getInspectionTemps,GetInspectionTempTrees,InspectionTempTreeImport} from '../../api/https'
import bus from '@/utils/eventBus.js';
import treeMenu from '@/components/base/treeMenu.vue'
import visitationList from '@/components/page/information/visitationList.vue'
import noData from '@/components/base/noData.vue'
import permissionMixin from '@/utils/permission.js'
export default ({
    name:'visitation',
    mixins: [permissionMixin],
    components:{cardBox,treeMenu,visitationList,noData},
    data() {
        return{
            stationId:sessionStorage.getItem("stationId"),
            currentName:'1',
            TempTreeList:[],
            currentBoxId:'',
            templateAsForm:{
                name: ''
            },
            dialogAsTemp:false,
            dialogTitle:'',
            menuByTempTree:[],
            menuByTempEdit:false,
            menuByTempLevel:'',
            menuFormByTemp:{
                treeName: '',
                request: ''
            },
            dialogMenuVisibleByTemp:false,
            importTempDialog:false,
            moduleSelectList:[],
            moduleSelect:'',
            importTreeList:[],
            moduleSelectData:{},
            showTabTwo:false,
            showTabOne:false,
        }
    },
    created(){
        this.initBasin()
        this.initPermissions()
        this.getInspectionTemp();
    },
    activated(){
        this.initBasin()
        const newStationId = sessionStorage.getItem("stationId");
        if (this.stationId != newStationId) {
            this.stationId = newStationId;
            this.getInspectionTemp()
        }
    },
    deactivated(){
       bus.$off('station-changed', this.handleStationChanged);
    },
    beforeDestroy(){
        this.TempTreeList = [];
        this.menuByTempTree = [];
        this.importTreeList = [];
        this.moduleSelectList = [];
    
        if (this.$refs.templateAsForm) {
            this.$refs.templateAsForm.resetFields();
            this.$refs.templateAsForm = null;
        }
    },
    computed: {
        shouldShowTabOne() {
            return this.currentName === '1' && this.showTabOne
        },
        shouldShowTabTwo() {
            return this.currentName === '2' && this.showTabTwo
        },
    },
    methods:{
        initBasin() {
            bus.$emit('showBasin', true);
            bus.$off('station-changed', this.handleStationChanged);
            bus.$on('station-changed', this.handleStationChanged);
        },
        handleStationChanged(newStationId, targetRoute) {
            if (!targetRoute || targetRoute === this.$route.name) {
                this.stationId = newStationId;
                this.getInspectionTemp()
            }
        },
        initPermissions() {
            const perm27 = this.getPermissions(27)
            const perm28 = this.getPermissions(28)
            
            this.showTabOne = !!(perm27.permission && perm27.permission.moduleId == 27)
            this.showTabTwo = !!(perm28.permission && perm28.permission.moduleId == 28)
            
            if (this.showTabOne) {
                ({showRoleAdd: this.showRoleModuleAdd, showRoleDel: this.showRoleModuleDel, showRoleEdit: this.showRoleModuleEdit} = perm27)
            }
            
            this.currentName =  this.showTabTwo ? '2' : this.showTabOne ? '1' :''
        },
        getInspectionTemp(){
            getInspectionTempsnew().then(res=>{
                if(res.isSuccess && res.data &&  res.data.length > 0){
                    this.TempTreeList = res.data
                    this.currentBoxId = res.data[0].id
                    this.getTreeData()
                    
                }else{
                    this.currentBoxId = ''
                    this.TempTreeList = []
                }
            })
        },
        handleChangeTempTreeItem(data){
            this.currentBoxId = data.id
            this.getTreeData()
        },
        getTreeData(){
            inspectionDataGetTree({
                StationID:this.stationId,
                InspectionTypeID:this.currentBoxId
            }).then(res=>{
                if(res.isSuccess){
                    this.menuByTempTree = res.data || []
                }else{
                    this.menuByTempTree = []
                }
            })
        },
        handleSaveAsTempDialog(data){
            this.templateAsForm = {...data}
            this.dialogAsTemp = true
            this.dialogTitle = '设置成模板'
        },
        handleCancelAsTemp(){
            this.templateAsForm = {}
            this.dialogAsTemp = false
            this.dialogTitle = ''
            this.$refs.templateAsForm && this.$refs.templateAsForm.resetFields();
        },
        handleEditAsTempDialog(data){
            this.templateAsForm = {...data}
            this.dialogAsTemp = true
            this.dialogTitle = '修改'
        },
        handleSaveAsTemp(){
            this.$refs['templateAsForm'].validate((valid) => {
                if (valid) {
                   if(this.dialogTitle == '设置成模板'){
                        SaveAsTemp({
                            inspectionTypeID:this.templateAsForm.id,
                            stationID:this.stationId,
                            tempName:this.templateAsForm.name
                        }).then(res=>{
                            if(res.isSuccess){
                                this.handleCancelAsTemp()
                                this.getInspectionTemp()
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        })
                    }else if(this.dialogTitle == '新增'){
                        InspectionTypeAdd({
                            id:0,
                            name:this.templateAsForm.name,
                            stationID:this.stationId
                        }).then(res=>{
                            if(res.isSuccess){
                                this.handleCancelAsTemp()
                                this.getInspectionTemp()
                            }else{
                            this.$message.error(res.errorMessage)
                            }
                        })
                    }else if(this.dialogTitle == '修改'){
                        InspectionTypeEdit(this.templateAsForm).then(res=>{
                            if(res.isSuccess){
                                this.handleCancelAsTemp()
                                this.getInspectionTemp()
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },

        handleDelAsTempDialog(data){
            this.$confirm(`确认删除名称为 ${data.name} 的模板？`,'提示',{
                type: 'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
                InspectionTypeDel(data.id).then(res=>{
                    if(res.isSuccess){
                        this.getInspectionTemp()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {}); 
        },
        handleAddMenubyTemp(data,isEdit,level){
            this.menuByTempEdit = isEdit
            this.menuByTempLevel = level || ''
            if(isEdit){
                const _editData = Object.assign({},data.node)
                this.menuFormByTemp = {..._editData}
            }else{
                this.menuFormByTemp = {
                    id: 0,
                    treeID:0,
                    treeName:'',
                    upTree: level == 1 ? data.node.upTree || 0 : data.node.treeID,
                    isBottom:0,
                    valueID:null,
                    inspectionTypeID:this.currentBoxId || 0,
                    request:''
                }
            }
            this.dialogMenuVisibleByTemp = true
        },
        handleCloseDialogMenu(){
            this.dialogMenuVisibleByTemp = false
            this.menuFormByTemp = {}
        },
        handleSaveDialogMenu(){
            this.$refs['menuFormByTemp'].validate((valid) => {
                if (valid) {
                    if(this.menuByTempEdit){
                        InspectionTreeEdit(this.menuFormByTemp).then(res=>{
                            if(res.isSuccess){
                                this.handleCloseDialogMenu()
                                this.getTreeData()
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        })
                    }else{
                        const _data = {
                            id: this.menuFormByTemp.id || 0,
                            treeID: this.menuFormByTemp.treeID || 0,
                            stationID: this.stationId,
                            treeName:this.menuFormByTemp.treeName,
                            upTree: this.menuFormByTemp.upTree || 0,
                            isBottom: this.menuFormByTemp.isBottom || 0,
                            valueID:null,
                            inspectionTypeID:this.currentBoxId || 0,
                            request:this.menuFormByTemp.request || ''
                        }
                        InspectionTreeAdd(_data).then(res=>{
                            if(res.isSuccess){ 
                                this.handleCloseDialogMenu()
                                this.getTreeData()
                            }else{
                                this.$message.error(res.errorMessage)
                            }
                        }) 
                    }
                } else {
                    return false;
                }
            });
            
        },
        handleDelMenubyTemp(data){
            this.$confirm(`确认删除名称为 ${data.lable} 的节点？`,'提示',{
                type:'warning',
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonClass: 'el-button--danger',
            }).then(() => {
            InspectionTreeDel({ID:data.node.id}).then(res=>{
                if(res.isSuccess){
                    this.getTreeData()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
            }).catch(() => {}); 
        },
        handleImportTempTree(){
            this.importTempDialog = true
            this.getModelSelect()
        },
        getModelSelect(){
            getInspectionTemps().then(res=>{
                if(res.isSuccess && res.data &&  res.data.length > 0){
                    this.moduleSelectList = res.data
                    this.handleChangeImportTree(res.data[0].tempID)
                }else{
                    this.TempTreeList = []
                }
            })
        },
        handleChangeImportTree(val){
            this.moduleSelect = val
            GetInspectionTempTrees({
                TempID:val
            }).then(res=>{
                if(res.isSuccess && res.data && res.data.length > 0){
                    this.importTreeList = res.data
                }else{
                    this.importTreeList = []
                }
            })
        },
        handleDialogLeftClick(data){
            this.moduleSelectData = {...data}
        },
        handleImportTemp(tp){
            InspectionTempTreeImport({
                stationID:this.stationId,
                TempID:this.moduleSelect,
                tp:tp,
                InspectionTypeID:this.currentBoxId
            }).then(res=>{
                if(res.isSuccess){
                    this.onImportModuleSuccess()
                }else{
                    // 后端非得让用汉字匹配
                    const tips = '已有巡视指标，导入将覆盖原有巡视指标，并清空此电站所有已录入的巡视数据，是否继续导入'
                    if(res.errorMessage == tips){
                        this.$confirm(tips, '提示', {
                            confirmButtonText: '是',
                            cancelButtonText: '否',
                            type: 'warning'
                        }).then(() => {
                            this.handleImportTemp(1)
                        }).catch(() => {});
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                }
            })
        },
        onImportModuleSuccess(){
            this.getTreeData()
            this.importTempDialog = false
            this.importTreeList = []
            this.moduleSelect = ''
            this.moduleSelectData = {}
        }
    }
})
</script>

<style scoped lang="scss">
.content{
    display: grid;
    grid-template-columns: 1fr 560px;
}
.left-wrapper-con{
    width: 100%;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin-top: 8px;
    max-height: calc(100vh - 165px);
    overflow: auto;
    padding-right: 12px;
}
.right-wrapper{
    height: calc(100vh - 185px);
    margin-top: 10px;
} 
.menu-wrapper{
    
    .table-tips{
        margin:10px 10px 0 10px;
    }
    .tree-wrapper{
        height: calc(100vh - 300px);
    overflow-y:auto;
    }
}
.xsItem{
    height: 170px;
    padding:20px;
    box-sizing: border-box;
    background: url('../../assets/image/1259.png') no-repeat 8px 0px rgba(255,255,255,.6);
    background-size: 120px 90px;
    position: relative;
    &:hover{
        cursor: pointer;
    }
    .name{
        height: 20px;
        font-weight: bold;
        margin:70px 0 0 5px;
    }
    .select{
        position: absolute;
        right:10px;
        top:10px;
        font-size: 36px;
        color:#409eff;
    }
}
.current{
    height: 170px;
    padding:20px;
    box-sizing: border-box;
    background: url('../../assets/image/0487.png') no-repeat 8px 14px rgba(255,255,255,1);
    background-size: 100px 60px;
    position: relative;
}
.xsItemNew{
    width:260px;
    height: 170px;
    margin: 0 10px 10px 0px;
    padding:20px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-content: center;
}
.btn-group{
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    margin-top:20px
}
.menuList-wrapper{
    height: calc(100vh - 400px);
    overflow-y:auto ;
}
.btnGroup{
    width: 100%;
    display: flex;
    justify-content: end;
}
.top-content{
    width: 99%;
    height: 180px;
    padding:10px;
    box-sizing: border-box;
    margin:10px 10px 10px 0;
    background: #fff;
    border-radius: 10px;
    .bg{
        width: 100%;
        height: 100%;
        background: url('../../assets/image/title-bg2.png') no-repeat center left;
        background-size: 100% 100%;
        .text{
            padding:40px 0 0 130px;
            font-size: 26px;
            font-weight: bold;
            color:#333;
            span{
                color:#2a5de7;
            }
        }
        .addBtn{
            margin:20px 0 0 130px;
        }
    }
    
}

// 响应式设计
@media (max-width: 1800px) {
.left-wrapper-con{
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-top: 8px;
    max-height: calc(100vh - 165px);
    overflow: auto;
    padding-right: 12px;
}}

@media (max-width: 1500px) {
.left-wrapper-con{
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    margin-top: 8px;
    max-height: calc(100vh - 165px);
    overflow: auto;
    padding-right: 12px;
}}


</style>
